/*
 * @Description: 分组设置组件
 * @Author: zzt
 * @Date: 2022-10-26 19:02:38
 * @LastEditTime: 2022-10-31 17:38:57
 */

import { Key, useCallback, useEffect, useState } from 'react';
import { Alert, Button, Form, Transfer } from 'antd';
import classNames from 'classnames/bind';
import update from 'immutability-helper';
import { QUERY_METADATA_GROUP } from '@/view/system/Metadata/constants';
import { DndProvider } from 'react-dnd';
import TransferSelectItem from './TransferSelectItem';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { fetchMetadata } from '@/api/metadata';
import { useAutoIncreaseContext } from '../contexts/AutoIncreaseContext';
import type { ICoordinate } from '@/interfaces/global';
import type { IGroupFieldList } from '@/api/rulesettings/groupSortRule';
import styles from '../styles/panes.module.scss';

const cx = classNames.bind(styles);

const GroupingSettings = () => {
  const { selectAT, selectLevel, commonRule, saveGroupSortRuleFunc } = useAutoIncreaseContext();
  const [form] = Form.useForm();

  // 元数据列表
  const [fieldList, setFieldList] = useState([]);
  // 已选择字段列表
  const [selectFieldList, setSelectFieldList] = useState([]);
  // 穿梭框选中的项目key集合（穿梭框右侧）
  const [targetKeys, setTargetKeys] = useState<string[]>([]);
  // 穿梭框右侧渲染的项目列表，用于右侧项目渲染及提交提交
  const [targetItems, setTargetItems] = useState<IGroupFieldList[]>([]);
  // 选中项目的key集合
  const [selectedKeys, setSelectedKeys] = useState([]);
  // 保存按钮是否可点击标志
  const [saveFlag, setSaveFlag] = useState<boolean>(false);

  useEffect(() => {
    setTargetKeys([]);
    setTargetItems([]);
    setSelectedKeys([]);
    setSaveFlag(false);
    if (selectLevel?.level) {
      const coordinate: ICoordinate = {
        atCode: selectAT.atCode,
        atType: selectAT.atType,
        level: selectLevel?.level || ''
      };

      const fieldQuery = {
        metadataFieldType: QUERY_METADATA_GROUP,
        coordinate
      };

      // 获取所有元数据
      fetchMetadata(fieldQuery).then((res) => {
        setFieldList(
          res.data.map((item: any) => {
            item.key = item.id;
            item.sortType = item.sortType || 0;
            return item;
          })
        );
      });
    }
  }, [selectLevel]);

  useEffect(() => {
    if (commonRule?.groupFieldResultList?.length > 0) {
      setSelectFieldList(commonRule.groupFieldResultList);
    } else {
      setSelectFieldList([]);
    }
  }, [commonRule]);

  useEffect(() => {
    setTargetKeys(selectFieldList.map((item: any) => item.fieldId));
    setTargetItems(
      selectFieldList.map((item: any) => ({
        ...item,
        key: item.fieldId
      }))
    );
  }, [selectFieldList]);

  /**
   * @description: 拖拽选中的条目触发，在此更新list
   */
  const moveSelect = useCallback((dragIndex: number, hoverIndex: number) => {
    console.log('moveSelect', dragIndex, hoverIndex);
    setTargetItems((state: any) =>
      update(state, {
        $splice: [
          [dragIndex, 1],
          [hoverIndex, 0, state[dragIndex]]
        ]
      })
    );
  }, []);

  /**
   * @description: 选项在两栏之间转移时的回调函数,direction='right' 时为增加，direction='left' 时为删除
   * @param {any} nextTargetKeys 右侧框的key集合
   */
  const onChange = (nextTargetKeys: any) => {
    setSaveFlag(true);
    setTargetKeys(nextTargetKeys);
    setTargetItems(
      nextTargetKeys.reverse().map((key: number | string) => {
        const fieldItem = fieldList.find((item) => item.id === key) || {};
        const listItem = selectFieldList.find((lItem: any) => lItem.fieldId === key) || {};
        return { ...fieldItem, ...listItem };
      })
    );
  };

  /**
   * @description: 选中项发生改变时的回调函数，用于项目选中的展示，设置为 单选
   * @param {function} sourceSelectedKeys 左侧选中
   * @param {function} targetSelectedKeys 右侧选中
   */
  const onSelectChange = (sourceSelectedKeys: Key[], targetSelectedKeys: Key[]) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  /**
   * @description: 提交表单，触发表单提交事件
   */
  const submitFunc = () => {
    form.submit();
  };
  /**
   * @description: 保存分组设置
   */
  const onFinish = () => {
    const groupFieldList: IGroupFieldList = targetItems.map((item: any, idx: number) => ({
      sortNo: idx,
      fieldId: item.id || item.fieldId,
      required: !!item.required
    }));

    console.log('onFinish', groupFieldList);
    saveGroupSortRuleFunc({ ...commonRule, groupFieldList });
  };

  /**
   * @description: 生成可拖拽列表
   */
  const renderSelect = useCallback((selectItem: any, listProps: any, index: number, onChange) => {
    return (
      <TransferSelectItem
        {...listProps}
        key={selectItem.key}
        index={index}
        item={selectItem}
        onChange={onChange}
        moveSelect={moveSelect}
        type={1}
      />
    );
  }, []);

  return (
    <div className={cx('auto-filing--container')}>
      <div className={cx('tips')}>
        <Alert
          description="为了给档案人员的录入工作提供方便，利用流水号自增功能可以设置某个字段按照设置的规则自动增长。
          默认长度是用来控制自增字段的形式，设置默认长度为3。分组长度是控制自增字段累加的规则，相同的分组条件下才开始计算组内自增。"
          type="info"
          showIcon
          closable
        />
      </div>
      <div className={cx('tabs-wrap')}>
        <div className={cx('filing-pane')}>
          <div className={cx('filing-header')}>
            <div className={cx('title')}>{selectLevel.levelName}-分组设置</div>
            <div className={cx('operate')}>
              <Button
                disabled={!saveFlag}
                onClick={() => {
                  submitFunc();
                }}
              >
                保存
              </Button>
            </div>
          </div>
          <Form
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 14 }}
            labelAlign={'left'}
            preserve={false}
            form={form}
            size="small"
            onFinish={onFinish}
          >
            <Form.Item labelCol={{ span: 24 }} wrapperCol={{ span: 20 }}>
              <Transfer
                dataSource={fieldList}
                titles={['待选排序字段', '已选排序字段']}
                listStyle={{
                  width: '50%',
                  height: 320
                }}
                targetKeys={targetKeys}
                selectedKeys={selectedKeys}
                onChange={onChange}
                onSelectChange={onSelectChange}
                render={(item) => ({ label: item.field_desc, value: item.id })}
                showSelectAll={false}
              >
                {(listProps) => {
                  if (listProps.direction === 'right') {
                    return (
                      <DndProvider backend={HTML5Backend}>
                        <div className="ant-transfer-list-content">
                          {targetItems.map((item: any, idx: number) =>
                            renderSelect(item, listProps, idx, setSaveFlag)
                          )}
                        </div>
                      </DndProvider>
                    );
                  }
                }}
              </Transfer>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};

export default GroupingSettings;
